from django import template
from django.utils.html import escape

from satchmo_tuning.models import CategoryTuning

register = template.Library()

def _build_list(current_category, categories, category_to_expand=None, expand_all=False):

    def build_line(category, category_to_expand):

        children = CategoryTuning.objects.filter(parent=category)
        
        if not (category.active or children):
            return u''

        if expand_all  or  category == category_to_expand:
            expanded = _build_list(current_category, children)
        else:
            expanded = u''

        classes = []
        if children:
            classes.append('has_children')
        if category == current_category:
            classes.append('current')
        if classes:
            css_class = ' class="%s"' % ' '.join(classes)
        else:
            css_class = ''

        return u'<li%s><a href="%s">%s</a>%s</li>' % (
                      css_class,
                      category.get_absolute_url(), 
                      escape(category.translated_name()),
                      expanded)

    lines = [build_line(category, category_to_expand) for category in categories]
    if lines:
        return u'<ul>' + u''.join(lines) + u'</ul>'
    else:
        return u''


def sibling_category_tree(id=None):
    """
    Creates an unnumbered list of the sibling categories.
    """
    category = CategoryTuning.objects.get(id=id)
    parents = category.parents()

    if len(parents) == 0:
        siblings = CategoryTuning.objects.filter(parent=category)
        category_to_expand = None
    elif len(parents) == 1:
        siblings = CategoryTuning.objects.filter(parent=category.parent)
        category_to_expand = category
    else:
        siblings = CategoryTuning.objects.filter(parent=category.parent.parent)
        category_to_expand = category.get_parent()

    return _build_list(category, siblings, category_to_expand)

register.simple_tag(sibling_category_tree)


def root_category_tree(id):
    """
    Creates an expanded unnumbered list of the all categories under category's root.
    """
    category = CategoryTuning.objects.get(id=id)
    parents = category.parents()
    if len(parents) == 0:
        root_category = category
    else:
        root_category = parents[0]

    return _build_list(category, CategoryTuning.objects.filter(parent=root_category), expand_all=True)

register.simple_tag(root_category_tree)

